package org.example.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.alibaba.nacos.shaded.com.google.gson.annotations.JsonAdapter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.example.constant.MsgConstant;
import org.example.domain.GoodsAddress;
import org.example.domain.User;
import org.example.domain.esdomain.UserIndex;
import org.example.domain.vo.AppUserPojo;
import org.example.domain.vo.MineUserDateil;
import org.example.mapper.GoodsAddressMapper;
import org.example.mapper.UserMapper;
import org.example.pojo.PageParams;
import org.example.repository.UserRepository;
import org.example.result.PageResult;
import org.example.service.IUserService;
import org.example.util.OnlyId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

import static org.example.constant.mqConstant.*;

/**
 * 用户操作
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private GoodsAddressMapper addressMapper;

    private static final String USERNAME = "userName";
    private static final String ACCOUNT = "account";
    private static final String CREATETIME = "createTime";
    private static final String SEX = "sex";
    private static final String IDENTIFYING = "identifying";

    /**
     * 分页查询不同类型的用户
     *
     * @param params 分页参数
     */
    @Override
    public PageResult<UserIndex> getUserListByIdentifying(PageParams<UserIndex> params) {
        PageResult<UserIndex> pageResult = new PageResult<>();
        UserIndex userIndex = params.getQueryParams();
        //分页
        PageRequest pageRequest = PageRequest.of(params.getPageNum(), params.getPageSize());
        //构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.hasText(userIndex.getUserName())) {
            boolQuery.must(QueryBuilders.matchQuery(USERNAME, userIndex.getUserName()));
        }
        if (userIndex.getSex() != null) {
            boolQuery.must(QueryBuilders.termQuery(SEX, userIndex.getSex()));
        }
        if (userIndex.getIdentifying() != null) {
            boolQuery.must(QueryBuilders.termQuery(IDENTIFYING, userIndex.getIdentifying()));
        }
        queryBuilder.withQuery(boolQuery);
        queryBuilder.withPageable(pageRequest);
        //排序
        queryBuilder.withSort(SortBuilders.fieldSort(CREATETIME).order(SortOrder.DESC));
        SearchHits<UserIndex> userIndexSearchHits = restTemplate.search(queryBuilder.build(), UserIndex.class);
        //总数
        long totalHits = userIndexSearchHits.getTotalHits();
        //详细数据
        List<SearchHit<UserIndex>> searchHits = userIndexSearchHits.getSearchHits();
        List<UserIndex> userIndexList = new ArrayList<>();
        for (SearchHit<UserIndex> searchHit : searchHits) {
            UserIndex content = searchHit.getContent();
            userIndexList.add(content);
        }
        pageResult.setTotal(totalHits);
        pageResult.setRows(userIndexList);
        return pageResult;
    }

    /**
     * 查询用户详细信息
     *
     * @param id 用户id
     */
    @Override
    public MineUserDateil getUserDetail(String id) {
        Optional<UserIndex> userIndex = userRepository.findById(Long.valueOf(id));
        return new MineUserDateil(userIndex.get());
    }

    /**
     * 新增用户
     *
     * @param user 用户信息
     */
    @Override
    public String addUser(User user) {
        String userId = OnlyId.nextId().toString();
        user.setId(userId);
        user.setCreateUser(null);
        user.setCreateTime(new Date());
        boolean isSave = this.save(user);
        if (isSave) {
            //给mq发送消息同步索引库
            rabbitTemplate.convertAndSend(USER_EXCHANGE_NAME, ADD_KEY, userId);
            return MsgConstant.SUCCESS;
        }
        return MsgConstant.FAIL;
    }

    /**
     * 修改用户
     *
     * @param user 用户信息
     */
    @Override
    public String editUser(User user) {
        user.setUpdateUser(null);
        user.setUpdateTime(new Date());
        boolean isEdit = this.updateById(user);
        if (isEdit) {
            //mq发送修改索引库消息
            rabbitTemplate.convertAndSend(USER_EXCHANGE_NAME, EDIT_KEY, user.getId());
            return MsgConstant.SUCCESS;
        }
        return MsgConstant.FAIL;
    }

    /**
     * 批量删除用户
     *
     * @param ids 用户id
     */
    @Override
    public String removeUser(String ids) {
        if (ids.contains(",")) {
            String[] splIds = ids.split(",");
            if (splIds.length > 0) {
                List<User> delUserList = new ArrayList<>();
                for (String id : splIds) {
                    //删除数据库数据
                    User user = new User();
                    user.setId(id);
                    user.setUpdateUser(null);
                    user.setUpdateTime(new Date());
                    user.setDelFlag(1);
                    delUserList.add(user);
                }
                if (CollectionUtil.isNotEmpty(delUserList)) {
                    boolean isDel = this.updateBatchById(delUserList);
                    if (isDel) {
                        //删除索引库用户
                        List<String> idList = Arrays.asList(splIds);
                        for (String id : idList) {
                            rabbitTemplate.convertAndSend(USER_EXCHANGE_NAME, EDIT_KEY, id);
                        }
                        return MsgConstant.SUCCESS;
                    }
                }
            }
        }
        return MsgConstant.FAIL;
    }

    /**
     * 获取app用户详细信息
     *
     * @param userId 用户id
     */
    @Override
    public AppUserPojo getAppUserDetailData(String userId) {
        //获取用户信息
        Optional<UserIndex> userIndex = userRepository.findById(Long.valueOf(userId));
        AppUserPojo appUserPojo = new AppUserPojo(userIndex.get());
        //获取收货地址信息
        LambdaQueryWrapper<GoodsAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsAddress::getUserId, userId);
        queryWrapper.eq(GoodsAddress::getDelFlag, 0);
        List<GoodsAddress> list = addressMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            appUserPojo.setGoodsAddressList(list);
        }
        return appUserPojo;
    }
}
